package cn.ggb.oss.service.impl;

import cn.ggb.oss.service.OssService;
import cn.ggb.oss.utils.ConstantPropertiesUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
    @Override
    public String uploadFileAvatar(MultipartFile file) {
        String endpoint = ConstantPropertiesUtil.END_POINT;
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
        // 填写Bucket名称，例如examplebucket。
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;


        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            //获取上传文件的输入流
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
            //获取文件名称
            String filename = file.getOriginalFilename();
            //让文件名称唯一
            String uuid = UUID.randomUUID().toString().replace("-","");
            filename = uuid+filename;
            //把上传的文件分类上传
            String datePath = new DateTime().toString("yyyy/MM/dd");
            filename = datePath + "/"+filename;
            // 创建PutObject请求。
            ossClient.putObject(bucketName, filename, inputStream);
            //关闭OSSClient
            ossClient.shutdown();

            String url = "http://"+bucketName+"."+endpoint+"/"+filename;

            return url;
        } catch (IOException e) {
        }

        return null;
    }
}
